#include "swagme.h"
#include "Sprite.h"

Sprite::Sprite(const char *file) :
    pSpriteSurface(NULL),
    mnNumAnimations(0), mnNumFrames(0)
{
  int len = strlen(file);
  SpriteImageFile = new char[len];
  if (SpriteImageFile)
    strcpy(SpriteImageFile,file);
  else
    cerr << "Sprite error: SpriteImageFile not allocated\n" << endl;

  pSpriteSurface = IMG_Load(SpriteImageFile);
  if (!pSpriteSurface) {
    cerr << "Sprite error: Unable to load sprite image: %s\n" << SDL_GetError() << endl;
    exit(1);
  }

  Frame.x=0;
  Frame.y=0;
  Frame.w=SPRITE_SIZE_X;
  Frame.h=SPRITE_SIZE_Y;

  mnNumAnimations = (pSpriteSurface->h) / SPRITE_SIZE_Y;
  mnNumFrames = (pSpriteSurface->w) / SPRITE_SIZE_X;

  cout << "Sprite loaded from '" << SpriteImageFile << "' has " <<
    mnNumAnimations << " animations and " << mnNumFrames << " frames" << endl;
}

int Sprite::Blit(SDL_Surface *dst, int x, int y) {
  if (!dst)
    cerr << "Sprite error: invalid destination surface\n" << endl;
  if (!pSpriteSurface)
    cerr << "Sprite error: Sprite not initialized\n" << endl;
  SDL_Rect dstRect;
  dstRect.x = x - SPRITE_SIZE_X/2;// + PLAYER_WIDTH/2 ; // TO DO: restore this once cdr is fixed?
  dstRect.y = y + PLAYER_HEIGHT - SPRITE_SIZE_Y;
  dstRect.w = Frame.w;
  dstRect.h = Frame.h;
  return SDL_BlitSurface(pSpriteSurface, &Frame, dst, &dstRect);
}

int Sprite::Draw(int animationIndex, int frameIndex, SDL_Surface *dst, int x, int y) {
  Frame.x = Frame.w * frameIndex;
  Frame.y = Frame.h * animationIndex;
  return Blit(dst, x, y);
}

Sprite::~Sprite() {
  if (SpriteImageFile) delete[] SpriteImageFile;
  if (pSpriteSurface) SDL_FreeSurface(pSpriteSurface);
}
